package com.weng.coder.service.convertor.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;

import com.weng.coder.service.convertor.ConvertCommand;
import com.weng.coder.service.convertor.Convertor;



/**
 * 转换器
 *
 * @version 
 * @author wengzhonghui  2017年7月12日 上午11:18:52
 * 
 */
@Slf4j
public abstract class AbstractConvertor implements Convertor {

    private List<ConvertCommand> commands = new ArrayList();

    public void registerCommand(ConvertCommand... commands) {
        this.commands.addAll(Arrays.asList(commands));
    }

    @Override
    public File convert(File from, File to, String code, String name) throws IOException {
        if (to == null) {
            to = new File(from.getParent(), code);
        }
        Collection<File> files = FileUtils.listFilesAndDirs(from, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
        for (File file : files) {
            String path = file.getPath();
            String filename = file.getName();
            String content = null;
            if (file.isFile()) {
                content = IOUtils.toString(new FileInputStream(file), "UTF8");
            }
            
            ConvertedFile cf = new ConvertedFile(path, filename, content);
            for (ConvertCommand command : this.commands) {
                log.debug("run command : " + command.getClass().getName());
                command.process(cf, code != null && code.trim().length() > 0 ? code : to.getName(), name);
            }
            
            cf.replacePath(from.getPath(), to.getPath());
            cf.makeFile();
        }
        
        return to;
    }
}
